package controller;

import pojo.Goods;
import service.ICategoryService;
import service.IGoodsService;
import service.IUserService;
import service.impl.CategoryServiceImpl;
import service.impl.GoodsServiceImpl;
import service.impl.UserServiceImpl;
import utils.NoLoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "IndexServlet", urlPatterns = "")
public class IndexServlet extends HttpServlet {
    private final int defaultPageIndex = 1;
    private final int defaultPageSize = 16;
    private IGoodsService goodsService;
    private ICategoryService categoryService;
    private IUserService userService;

    @Override
    public void init() throws ServletException {
        goodsService = new GoodsServiceImpl();
        categoryService = new CategoryServiceImpl();
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NoLoginUtil.doVerify(request);
        String categoryName = request.getParameter("category-name");
        int pageIndex = request.getParameter("page-index") != null ? Integer.parseInt(request.getParameter("page-index")) : defaultPageIndex;
        int pageSize = request.getParameter("page-size") != null ? Integer.parseInt(request.getParameter("page-size")) : defaultPageSize;
        List<Goods> allGoods;
        List<Goods> defaultGoods;
        if (categoryName == null || "".equals(categoryName.trim())) {
            allGoods = goodsService.queryAllGoods();
        } else {
            allGoods = goodsService.queryGoodsByCategoryName(categoryName);
        }
        try {
            defaultGoods = allGoods.subList((pageIndex - 1) * pageSize, (pageIndex - 1) * pageSize + pageSize);
        } catch (IndexOutOfBoundsException e) {
            defaultGoods = allGoods.subList((pageIndex - 1) * pageSize, allGoods.size());
        }
        request.setAttribute("goods", defaultGoods);
        request.setAttribute("categories", categoryService.queryAllCategories());
        request.setAttribute("pageNum", allGoods.size() / defaultPageSize + 1);
        request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
    }
}
